package org.jeecg.modules.htxincailiao.industry.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.*;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.industry.constant.HTDateStatusEnum;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryMeeting;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustrySalon;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustrySalon;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustrySalonApply;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustrySalonService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryTagService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

import static org.jeecg.modules.htxincailiao.industry.constant.HTDateStatusEnum.PARTICIPATE;
import static org.jeecg.modules.htxincailiao.industry.constant.HTCheckCodeURLConstant.CHECK_CODE_URL_SALON;

/**
 * @Description: ht_industry_salon
 * @Author: jeecg-boot
 * @Date:   2021-11-01
 * @Version: V1.0
 */
@Api(tags="ht_industry_salon")
@RestController
@RequestMapping("/industry/hTIndustrySalon")
@Slf4j
public class HTIndustrySalonController extends JeecgController<HTIndustrySalon, IHTIndustrySalonService> {
	@Resource
	private IHTIndustrySalonService hTIndustrySalonService;

	@Resource
	private IHTIndustryTagService hTIndustryTagService;


	@Resource
	private IHTAccountService accountService;


	@Value(value = "${jeecg.path.upload}")
	private String uploadPath;

	/**
	 * 分页列表查询
	 *
	 * @param hTIndustrySalon
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_industry_salon-分页列表查询")
	@ApiOperation(value="ht_industry_salon-分页列表查询", notes="ht_industry_salon-分页列表查询")
	@RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryPageList(HTIndustrySalon hTIndustrySalon,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				hTIndustrySalon = JSONObject.parseObject(line, HTIndustrySalon.class);
				pageNo = oConvertUtils.isNotEmpty(hTIndustrySalon.getPageNo()) ? hTIndustrySalon.getPageNo() : pageNo;
				pageSize = oConvertUtils.isNotEmpty(hTIndustrySalon.getPageSize()) ? hTIndustrySalon.getPageSize() : pageSize;
			}
		}

//		Map<String, String[]> handleMap = FilterUtil.getSortMap(req, "start_time", "desc");
		Map<String, String[]> handleMap = FilterUtil.getSortMap(req, "sort", "asc");
		HTDateStatusEnum dateStatus = hTIndustrySalon.getDateStatus();
		switch (dateStatus){
			case RECENTLY:{
				String[] timeConditions= {DateUtils.date2Str(DateUtils.date_sdf.get( ))};
				handleMap.put("startTime_begin", timeConditions);
			}
			break;

			case PREVIOUS_PERIOD:
			{
				String[] timeConditions= {DateUtils.date2Str(DateUtils.date_sdf.get( ))};
				handleMap.put("endTime_end", timeConditions);
			}
			break;

			case ONGOING:
			{
				String[] timeConditions= {DateUtils.date2Str(DateUtils.date_sdf.get( ))};
				handleMap.put("startTime_end", timeConditions);
				handleMap.put("endTime_begin", timeConditions);
			}
			break;

			default:
				break;
		}

		if (dateStatus == PARTICIPATE){
			String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
			if(oConvertUtils.isNotEmpty(token)){
				String username = JwtUtil.getUsername(token);
				if (oConvertUtils.isNotEmpty(username)){
					HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
					if(oConvertUtils.isNotEmpty(user)){
						HTIndustrySalonApply salonApply = new HTIndustrySalonApply();
						salonApply.setApplyUserId(user.getId());

						Page<HTIndustrySalon> page = new Page<HTIndustrySalon>(pageNo, pageSize);
						IPage<HTIndustrySalon> salonPageList = hTIndustrySalonService.queryListByApplyUserId(page, user.getId(), hTIndustrySalon.getName());
						return Result.OK(salonPageList);
					}
					else {
						return Result.error("用户不存在");
					}
				}
				else {
					return Result.error("用户不存在");
				}

			}
			else {
				return Result.error("请先登录");
			}

		}
		else {
			QueryWrapper<HTIndustrySalon> queryWrapper =  QueryGenerator.initQueryWrapper(hTIndustrySalon, handleMap);
			queryWrapper.orderByDesc("create_time");
			Page<HTIndustrySalon> page = new Page<HTIndustrySalon>(pageNo, pageSize);
			IPage<HTIndustrySalon>  pageList = hTIndustrySalonService.page(page, queryWrapper);
			return Result.OK(pageList);
		}

	}
	/**
	 * 分页列表查询
	 *
	 * @param hTIndustrySalon
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_news-分页列表查询")
	@ApiOperation(value = "ht_news-分页列表查询", notes = "ht_news-分页列表查询")
	@RequestMapping(value = "/pc-home-list", method = {RequestMethod.GET, RequestMethod.POST})
	public Result<?> queryPCHomePageList(HTIndustrySalon hTIndustrySalon,
										 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
										 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
										 HttpServletRequest req) {
		if (req.getMethod().equals("POST")) {
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				hTIndustrySalon = JSONObject.parseObject(line, HTIndustrySalon.class);
				pageNo = oConvertUtils.isNotEmpty(hTIndustrySalon.getPageNo()) ? hTIndustrySalon.getPageNo() : pageNo;
				pageSize = oConvertUtils.isNotEmpty(hTIndustrySalon.getPageSize()) ? hTIndustrySalon.getPageSize() : pageSize;
			}
		}

		QueryWrapper<HTIndustrySalon> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustrySalon, req.getParameterMap());
//        queryWrapper.orderByDesc("update_time");
		queryWrapper.orderByDesc("is_home_recommended").orderByDesc("update_time");

		Page<HTIndustrySalon> page = new Page<HTIndustrySalon>(pageNo, pageSize);
		IPage<HTIndustrySalon> pageList = hTIndustrySalonService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hTIndustrySalon
	 * @return
	 */
	@AutoLog(value = "ht_industry_salon-添加")
	@ApiOperation(value="ht_industry_salon-添加", notes="ht_industry_salon-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HTIndustrySalon hTIndustrySalon) {
		try {
//			String content = CHECK_CODE_URL_EXHIBITION + "?"+hTIndustrySalon.getId();
//
//			String contentEncoded = URLEncoder.encode(content, "UTF-8");
//			String qrcodeUrl = createQrCodeFile(contentEncoded);
//			hTIndustrySalon.setCheckQrcodeUrl(qrcodeUrl);

			addSalonCheckQrcodeUrlIfNeed(hTIndustrySalon);

			hTIndustrySalonService.save(hTIndustrySalon);

			return Result.OK("添加成功！");
		}
		catch (Exception e) {
			throw new JeecgBootException("添加失败");
		}

	}

	private HTIndustrySalon addSalonCheckQrcodeUrlIfNeed(HTIndustrySalon hTIndustrySalon){
		if(oConvertUtils.isEmpty(hTIndustrySalon.getCheckQrcodeUrl()) || !hTIndustrySalon.getCheckQrcodeUrl().contains(CHECK_CODE_URL_SALON))
		{
			String content =  CHECK_CODE_URL_SALON + "?id="+hTIndustrySalon.getId();

//				String contentEncoded = URLEncoder.encode(content, "UTF-8");
			String qrcodeUrl = createQrCodeFile(content);
			hTIndustrySalon.setCheckQrcodeUrl(qrcodeUrl);

			return hTIndustrySalon;
		}

		return hTIndustrySalon;
	}

	private String createQrCodeFile(String content){
		try {
			byte[] bytes = QrCodeUtil.generatePng(content, 500, 500);
			String ctxPath = uploadPath;
			String fileName = null;
			String bizPath = "files";
			String nowDay = new SimpleDateFormat("yyyyMMdd").format(new Date());
			File file = new File(ctxPath + File.separator + bizPath + File.separator + nowDay);
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			fileName = "salon_qrcode_" + System.currentTimeMillis()+".png";
			String savePath = file.getPath() + File.separator + fileName;
			File saveFile = new File(savePath);
			FileCopyUtils.copy(bytes, saveFile);
			String dbpath = bizPath + File.separator + nowDay + File.separator + fileName;
			if (dbpath.contains("\\")) {
				dbpath = dbpath.replace("\\", "/");
			}
			return dbpath;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 *  编辑
	 *
	 * @param hTIndustrySalon
	 * @return
	 */
	@AutoLog(value = "ht_industry_salon-编辑")
	@ApiOperation(value="ht_industry_salon-编辑", notes="ht_industry_salon-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HTIndustrySalon hTIndustrySalon) {
		addSalonCheckQrcodeUrlIfNeed(hTIndustrySalon);
		hTIndustrySalonService.updateById(hTIndustrySalon);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_industry_salon-通过id删除")
	@ApiOperation(value="ht_industry_salon-通过id删除", notes="ht_industry_salon-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		hTIndustrySalonService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ht_industry_salon-批量删除")
	@ApiOperation(value="ht_industry_salon-批量删除", notes="ht_industry_salon-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hTIndustrySalonService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_industry_salon-通过id查询")
	@ApiOperation(value="ht_industry_salon-通过id查询", notes="ht_industry_salon-通过id查询")
	@RequestMapping(value = "/queryById", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryById(HttpServletRequest req, @RequestParam(name="id",required=false) String id) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				HTIndustrySalon hTIndustrySalon  = JSONObject.parseObject(line, HTIndustrySalon.class);
				id = hTIndustrySalon.getId();
			}
		}


		HTIndustrySalon hTIndustrySalon = hTIndustrySalonService.getById(id);
		if (oConvertUtils.isNotEmpty(hTIndustrySalon) &&
				oConvertUtils.isNotEmpty(hTIndustrySalon.getTagId())) {
			List<Object> list = new ArrayList<Object>();
			String[] tagIds = hTIndustrySalon.getTagId().split(",");
			if(oConvertUtils.isNotEmpty(tagIds)){
				for (String tagId : tagIds){
					String  tagName= hTIndustryTagService.getById(tagId).getName();
					JSONObject info = new JSONObject();
					info.put("tagId", tagId);
					info.put("tagName",tagName);
					list.add(info);
				}
				hTIndustrySalon.setTagInfos(list.toArray());
			}
		}

		if(hTIndustrySalon==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hTIndustrySalon);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param hTIndustrySalon
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HTIndustrySalon hTIndustrySalon) {
		return super.exportXls(request, hTIndustrySalon, HTIndustrySalon.class, "ht_industry_salon");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, HTIndustrySalon.class);
	}

}
